package com.arvato.wxwork.service.member;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.arvato.common.config_bean.WxworkConfig;
import com.arvato.common.https.WxworkMiniproOwnRequestUtil;
import com.arvato.common.util.ChineseCharacterUtil;
import com.arvato.common.util.EmojiFilter;
import com.arvato.common.util.JsonUtil;
import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.wxwork.bean.bean_do.member.WxworkExternalInfoDo;
import com.arvato.wxwork.bean.bean_do.member.WxworkMemberBindDo;
import com.arvato.wxwork.bean.bean_dto.WxworkFollowUserDto;
import com.arvato.wxwork.bean.bean_vo.member.WxworkExternalInfoVo;
import com.arvato.wxwork.bean.bean_vo.member.WxworkMemberBindVo;
import com.arvato.wxwork.bean.bean_vo.staff.WxworkStaffInfoVo;
import com.arvato.wxwork.mapper.member.WxworkExternalInfoMapper;
import com.arvato.wxwork.service.staff.WxworkStaffInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


@Service
@Transactional
public class WxworkExternalService {
	
	@Autowired
	private JsonUtil jsonUtil;	
	
	@Autowired
	private WxworkMiniproOwnRequestUtil wxworkMiniproOwnRequestUtil;	
	
	@Autowired
	private WxworkExternalInfoMapper wxworkExternalInfoMapper;
	
	@Autowired
	@Lazy
	private WxworkMemberBindService wxworkMemberBindService;
	
	@Autowired
	private WxworkStaffInfoService wxworkStaffInfoService;
	
	
	
	private Logger logger = LoggerFactory.getLogger(WxworkExternalService.class);

	/**
	 * 批量查询外部联系人信息(分页)
	 * @param query
	 * @param pageNum
	 * @param pageSize
	 */
	public PageData listExternalByQuery(Query query, Integer pageNum, Integer pageSize) {
		// 设置分页参数
		PageHelper.startPage(pageNum, pageSize);
		logger.info("开始查询客户列表。");
		List<WxworkExternalInfoVo> memberList = wxworkExternalInfoMapper.listExternalByQuery(query);
		logger.info("查询到客户人数:" + memberList.size());
		PageInfo<WxworkExternalInfoVo> pageInfo = new PageInfo<WxworkExternalInfoVo>(memberList);
		PageData pageData = new PageData(pageInfo.getTotal(), pageInfo.getList());
		return pageData;
	}
	
	/**
	 * 批量查询外部联系人信息(不分页)
	 * @param query
	 * @return
	 */
	public List<WxworkExternalInfoVo> listExternalByQuery(Query query) {
		List<WxworkExternalInfoVo> memberList = wxworkExternalInfoMapper.listExternalByQuery(query);
		return memberList;
	}
	
	/**
	 * 根据ID查询外部联系人信息
	 * @param query
	 * @return
	 */
	public WxworkExternalInfoVo getExternalById(String externalId) {
		return wxworkExternalInfoMapper.getExternalById(externalId);
	}
	
	/**
	 * 查询没有被分组的外部联系人(分页)
	 * @param staffId
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public PageData getNoGroupPeople(Query query, Integer pageNum, Integer pageSize) {
		// 设置分页参数
		PageHelper.startPage(pageNum, pageSize);
		List<WxworkExternalInfoVo> memberList = wxworkExternalInfoMapper.getNoGroupPeople(query);
		PageInfo<WxworkExternalInfoVo> pageInfo = new PageInfo<WxworkExternalInfoVo>(memberList);
		PageData pageData = new PageData(pageInfo.getTotal(), pageInfo.getList());
		return pageData;
	}
	
	/**
	 * 查询没有被分组的外部联系人(不分页)
	 * @param staffId
	 * @return
	 */
	public List<WxworkExternalInfoVo> getNoGroupPeople(Query query) {
		return wxworkExternalInfoMapper.getNoGroupPeople(query);
	}
	
	/**
	 * 更新外部联系人信息
	 * @param externalInfo
	 * @return
	 */
	public int update(WxworkExternalInfoDo externalInfo) {
		return wxworkExternalInfoMapper.update(externalInfo);
	}
	
	/**
	 * 新增一个外部联系人信息
	 * @param externalInfo
	 */
	public int insert(WxworkExternalInfoDo externalInfo) {
		return wxworkExternalInfoMapper.insert(externalInfo);
	}
	
	/**
	 * 异步更新或者插入外部联系人的数据
	 * @param allList
	 */
	public int ayncUpdate(WxworkExternalInfoDo wxworkExternalInfoDo) {
		int row = 0;
		// 首先检查当前的externalUserid是不是存在 存在就更新 否则就插入
		Query query = new Query();
		query.put("externalUserId", wxworkExternalInfoDo.getWxExternalUserid());
		query.put("brand", wxworkExternalInfoDo.getBrand());
		query.put("corpid", WxworkConfig.CORPID);
		List<WxworkExternalInfoVo> externalList = listExternalByQuery(query);
		if(externalList.size() != 0) {
			// 更新
			wxworkExternalInfoDo.setExternalId(externalList.get(0).getExternalId());
			row = wxworkExternalInfoMapper.update(wxworkExternalInfoDo);
		}else {
			// 插入
			row = wxworkExternalInfoMapper.insert(wxworkExternalInfoDo);
		}
		return row;
	}
	
	/**
	 * 根据外部联系人的userid查询详细信息
	 * @param externalUserId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public WxworkExternalInfoDo getRemoteExternalInfo(String externalUserId) {
		WxworkExternalInfoDo externalDo = new WxworkExternalInfoDo();
		// 首先要获取token
		String accessToken = wxworkMiniproOwnRequestUtil.getExternalContactAccessToken();
		// 查询改外部联系人的其他信息
		if(accessToken == null) {
			throw new RuntimeException("获取token失败");
		}
		Map<String, Object> resultMap = wxworkMiniproOwnRequestUtil.getExternalInfoById(externalUserId, accessToken);
		if("84061".equals(resultMap.get("errcode") + "") || "40096".equals(resultMap.get("errcode") + "")) {
			throw new RuntimeException("当前客户没有与任何员工建立好友关系,不是我们的外部联系人。");
		}
		if(!"0".equals(resultMap.get("errcode") + "")) {
			throw new RuntimeException("获取外部联系人详情失败" + jsonUtil.obj2String(resultMap));
		}
		Map<String, Object> externalInfoMap = (Map<String, Object>)resultMap.get("external_contact");
		externalDo.setAvatar(externalInfoMap.get("avatar") == null?"":externalInfoMap.get("avatar") + "");
		externalDo.setCorpFullName(externalInfoMap.get("corp_full_name") == null?"":externalInfoMap.get("corp_full_name") + "");
		externalDo.setCorpName(externalInfoMap.get("corp_name") == null?"":externalInfoMap.get("corp_name") + "");
		externalDo.setExternalProfile(externalInfoMap.get("external_profile") == null?"":externalInfoMap.get("external_profile") + "");
		externalDo.setGender(Integer.valueOf(externalInfoMap.get("gender") == null?"0":externalInfoMap.get("gender") + ""));
		String name = externalInfoMap.get("name") == null?"":externalInfoMap.get("name") + "";
		// 过滤昵称里面掉乱七八糟的表情字符
		if(EmojiFilter.containsEmoji(name)) {
			name = EmojiFilter.filterEmoji(name);
		}
		externalDo.setName(name);
		externalDo.setPosition(externalInfoMap.get("position") == null?"":externalInfoMap.get("position") + "");
		externalDo.setType(Integer.valueOf(externalInfoMap.get("type") == null?"1":externalInfoMap.get("type") + ""));
	//	externalDo.setUnionid(externalInfoMap.get("unionid") == null?"":externalInfoMap.get("unionid") + "");
		externalDo.setUpdateDate(new Date());
		// 外部联系人的企业微信好友
		Object followUser = resultMap.get("follow_user");
		if(followUser != null) {
			externalDo.setFollowUser(jsonUtil.obj2String(followUser));
		}
		return externalDo;
	}
	
	/**
	 * 同步外部联系人
	 * @return
	 */
	public int snycExternal() {
		List<WxworkExternalInfoVo> list = wxworkExternalInfoMapper.listExternalByQuery(null);
		for(WxworkExternalInfoVo externalVo : list) {
			try {
				WxworkExternalInfoDo externalDo = getRemoteExternalInfo(externalVo.getWxExternalUserid());
				externalDo.setExternalId(externalVo.getExternalId());
				update(externalDo);
				// 同步外部联系人的备注
				setRemark(externalDo.getExternalId()); 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list.size();
	}
	
	/**
	 * 设置外部联系人的备注
	 * @param externalId
	 */
	public void setRemark(String externalId) {
		WxworkExternalInfoVo externalVo = wxworkExternalInfoMapper.getExternalById(externalId);
		if(externalVo == null || externalVo.getFollowUser() == null) {
			return;
		}
		// 查询当前的externalId是否有绑定人员
		Query query = new Query();
		query.put("externalId", externalId);
		List<WxworkMemberBindVo> bindList = wxworkMemberBindService.listBindByQuery(query);
		// 如果当前人没有被绑定 方法不继续进行
		if(bindList.size() == 0) {
			return;
		}
		WxworkMemberBindVo bindVo = bindList.get(0);
		WxworkStaffInfoVo staffVo = wxworkStaffInfoService.getStaffById(bindVo.getStaffId());
		String userid = staffVo.getUserid();
		// 找出followuser里面他的bc给他的备注
		String remark = externalVo.getName();
		String followUser = externalVo.getFollowUser();
		try {
			List<WxworkFollowUserDto> staffDtoList = jsonUtil.str2List(followUser, WxworkFollowUserDto.class);
			for(WxworkFollowUserDto dto : staffDtoList) {
				if(dto.getUserid().equals(userid)) {
					if(dto.getRemark() != null && !dto.getRemark().trim().equals("")) {
						remark = dto.getRemark();
					}
				}
			}
			WxworkMemberBindDo bindDo = new WxworkMemberBindDo();
			bindDo.setBindId(bindVo.getBindId());
			bindDo.setRemark(remark);
			String remarkOrder = ChineseCharacterUtil.getSpells(String.valueOf(remark.charAt(0))).toUpperCase();
			bindDo.setRemarkOrder(remarkOrder);
			wxworkMemberBindService.update(bindDo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("更改客户备注出错", e);
		}
	}
	
	/**
	 * 检查外部联系人和员工是否是好友关系
	 * @param externalId
	 * @param staffId
	 * @return
	 * @throws Exception
	 */
	public boolean checkRelation(String externalId, String staffId) throws Exception {
		WxworkExternalInfoVo externalVo = getExternalById(externalId);
		WxworkStaffInfoVo staffVo = wxworkStaffInfoService.getStaffById(staffId);
		String externalUserId = externalVo.getWxExternalUserid();
		// 获取当前外部联系人的好友列表
		WxworkExternalInfoDo remoteExternalInfoDo = getRemoteExternalInfo(externalUserId);
		String followUser = remoteExternalInfoDo.getFollowUser();
		List<WxworkFollowUserDto> staffDtoList = jsonUtil.str2List(followUser, WxworkFollowUserDto.class);
		for(WxworkFollowUserDto dto : staffDtoList) {
			if(dto.getUserid().equals(staffVo.getUserid())) {
				return true;
			}
		}
		return false;
	}

}
